package internetware.windowsclient;


import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UnsupportedLookAndFeelException;

import sun.management.ManagementFactory;

import com.sun.management.OperatingSystemMXBean;

public class Client{
	Vector<String> v;
	UI u;
	private boolean stop;
	private boolean logged;
	private String server ;
	private String timeout ;
	private String sessionid;
	private String username;
	private String password;
	private String deviceid ;
	public static void main(String[] args)
	{
		try {
			javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}
		
		Client c = new Client();
		c.getSetting();
		c.u = c.new UI();
		c.u.init();
	}
	private void getSetting()
	{
		v = new Vector<String>();
		File file = new File("setting");
		if(!file.exists())
		{
			return ;
		}
		String tempString ;
		int line = 1;
		try {
			BufferedReader reader  = new BufferedReader(new FileReader(file));
			while ((tempString = reader.readLine()) != null){
					if(line ==1)
					{
						server = tempString;
					}
					else if(line ==2)
					{
						timeout = tempString;
					}
					else
					{
						v.add(tempString);
					}
					line++;
			}
			reader.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	private void writeSetting()
	{
		File file = new File("setting");
		if(file.exists())
		{
			file.delete();
		}
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(file));
			writer.write(server);
			writer.newLine();
			writer.write(timeout);
			writer.newLine();
			for(int i=0;i<v.size();i++)
			{
				writer.write(v.elementAt(i));
				if(i!=v.size()-1)
				{
					writer.newLine();
				}
			}
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private String login(){
		
		
		try {
			URL url = new URL(server);
			URLConnection conn = url.openConnection();
		    conn.setDoOutput(true);
		    
		    BufferedWriter printout;
		    printout = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
		    printout.write("operation:login");
		    printout.newLine();
		    printout.flush();
		    printout.write("user:"+username);
		    printout.newLine();
		    printout.flush();
		    printout.write("password:"+password);
		    printout.newLine();
		    printout.flush();
		    printout.write("deviceid:"+deviceid);
		    printout.newLine();
		    printout.flush();
		    printout.write("timeout:"+timeout);
		    printout.newLine();
		    printout.flush();
		    

		    
		    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		    String line = "";
		    StringBuffer sb = new StringBuffer();
		    while ((line = rd.readLine()) != null) {
		    	sb.append(line);
		    }
		    sessionid = sb.substring(sb.indexOf(":")+1);
		    return sb.toString();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    return "";
		
	}
	private String putContextInfo()
	{
		String info  =getContextInfo();
		URL url;
		try {
			url = new URL(server);
			URLConnection conn = url.openConnection();
		    conn.setDoOutput(true);
		    
		    BufferedWriter printout;
		    printout = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
		    printout.write("operation:putinfo");
		    printout.newLine();
		    printout.flush();
		    printout.write("sessionid:"+sessionid);
		    printout.newLine();
		    printout.flush();
		    //printout.write("info:memory={a=1,b=2}--os={a=3,b=4}--language={a=5,c=6}");
		    printout.write("info:"+info);
		    printout.newLine();
		    printout.flush();
		    

		    
		    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		    String line = "";
		    StringBuffer sb = new StringBuffer();
		    while ((line = rd.readLine()) != null) {
		    	sb.append(line);
		    }
		    return sb.toString();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "";
	}
	
	private String getContextInfo() {
		StringBuilder sb = new StringBuilder();
		
		//memory
		OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
		Long l = osmxb.getTotalPhysicalMemorySize()/(1024*1024);
		Long m = osmxb.getFreePhysicalMemorySize()/(1024*1024);
		String memory = "memory={total_memory="+l+"M,free_memory="+m+"M}";
		sb.append(memory);
		sb.append("--");
		
		//os
		String os = "os={name="+System.getProperty("os.name")+",patch_level="+System.getProperty("sun.os.patch.level")+"}";
		sb.append(os);
		sb.append("--");
		
		//language
		String language = "language={user_language="+System.getProperty("user.language")+",file_encoding="+System.getProperty("file.encoding")+"}";
		sb.append(language);
		sb.append("--");
		
		//screen
		String screen = "screen={width="+Toolkit.getDefaultToolkit().getScreenSize().width+",height="+Toolkit.getDefaultToolkit().getScreenSize().width+"}";
		sb.append(screen);
		return sb.toString();
	}

	class innerThread extends Thread{

		@Override
		public void run() {
			logged = false;
			while(!stop)
			{
				if(logged==true)
				{
					String res  = putContextInfo();
					System.out.println(res);
					if(!res.contains("ok"))
					{
						System.exit(0);
						break;
						
					}
				}
				else
				{
					String res  =login();
					System.out.println(res);
					if(!res.contains("sessionid"))
					{
						JOptionPane.showMessageDialog(null, res);
						UI u = new UI();
						u.init();
						break;
					}
					else
					{
						logged = true;
					}
					res  = putContextInfo();
					System.out.println(res);
					if(!res.contains("ok"))
					{
					
					}
				}
				int t = Integer.valueOf(timeout);
				try {
					Thread.sleep(1000*t);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
		
	}
	class UI{
		int w;
		int h;
		private JFrame frame;
		private JLabel lable1;
		private JLabel lable2;
		private JButton button1;
		private JButton button2;
		private JTextField user;
		private JPasswordField passwd;
		public void init()
		{
			frame = new JFrame("client");			
			frame.setSize(300, 100);
			w = (Toolkit.getDefaultToolkit().getScreenSize().width - 300) / 2;
			h = (Toolkit.getDefaultToolkit().getScreenSize().height - 100) / 2;
			frame.setLocation(w, h); 
			frame.setLayout(new GridLayout(3,2));
			lable1 = new JLabel("user");
			lable2 = new JLabel("password");
			button1 = new JButton("enter");
			button2 = new JButton("set");
			user = new JTextField();
			passwd = new JPasswordField();
			frame.getContentPane().add(lable1);
			frame.getContentPane().add(user);
			frame.getContentPane().add(lable2);			
			frame.getContentPane().add(passwd);
			frame.getContentPane().add(button1);
			frame.getContentPane().add(button2);
			button1.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					if(user.getText().length()==0||passwd.getPassword().length==0)
					{					
						return;
					}
					username = user.getText();
					password = new String(passwd.getPassword());
					boolean found = false;
					for(int i =0;i<v.size();i++)
					{
						String s = v.elementAt(i);
						if(s.contains(username))
						{
							deviceid = s.substring(s.indexOf(":")+1);
							found =true;
							break;
							
						}
					}
					if(found)
					{
						Run r = new Run(w,h);
						r.init();
						innerThread t = new innerThread();
						t.start();
						frame.dispose();
					}
					else
					{
						deviceID d = new deviceID(frame,username);
						d.init();
					}
					
				}
				
			});
			button2.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					
					stop = false;
					Set s = new Set(frame);
					s.init();
				}
				
			});
			frame.addWindowListener(new WindowListener(){

				@Override
				public void windowActivated(WindowEvent e) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void windowClosed(WindowEvent e) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void windowClosing(WindowEvent e) {
					// TODO Auto-generated method stub
					System.exit(0);
				}

				@Override
				public void windowDeactivated(WindowEvent e) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void windowDeiconified(WindowEvent e) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void windowIconified(WindowEvent e) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void windowOpened(WindowEvent e) {
					// TODO Auto-generated method stub
					
				}
				
			});
			frame.setVisible(true);
		}		
	}
	class deviceID
	{
		private String user;
		private JFrame parent;
		private JDialog dialog;
		private JLabel lable1;
		private JButton button1;
		private JButton button2;
		private JTextField text1;
		public deviceID(JFrame f,String u)
		{
			parent = f;
			user = u;
		}
		public void init()
		{
			dialog = new JDialog(parent,true);
			dialog.setSize(300, 100);
			dialog.setLocationRelativeTo(parent);
			dialog.setLayout(new GridLayout(2,2));
			lable1 = new JLabel("device id");
			button1 = new JButton("ok");
			button2 = new JButton("cancel");
			text1 = new JTextField();
			dialog.getContentPane().add(lable1);
			dialog.getContentPane().add(text1);
			dialog.getContentPane().add(button1);
			dialog.getContentPane().add(button2);
			button1.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					if(text1.getText().length()==0)
					{
						return ;
					}
					String deviceid = text1.getText();
					v.add(user+":"+deviceid);
					writeSetting();
					dialog.dispose();
				}
			});
			button2.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					
					dialog.dispose();
				}
				
			});
			dialog.setVisible(true);
		}
		                   
	}
	class Set
	{
		private JFrame parent;
		private JDialog dialog;
		private JLabel lable1;
		private JLabel lable2;
		private JButton button1;
		private JButton button2;
		private JTextField text1;
		private JTextField text2;
		public Set(JFrame f)
		{
			parent = f;
			
		}
		public void init()
		{
			dialog = new JDialog(parent,true);
			dialog.setSize(300, 100);
			dialog.setLocationRelativeTo(parent);
			dialog.setLayout(new GridLayout(3,2));
			lable1 = new JLabel("server");
			lable2 = new JLabel("timeout");
			button1 = new JButton("set");
			button2 = new JButton("cancel");
			text1 = new JTextField(server);
			text2 = new JTextField(timeout);
			dialog.getContentPane().add(lable1);
			dialog.getContentPane().add(text1);
			dialog.getContentPane().add(lable2);
			dialog.getContentPane().add(text2);
			dialog.getContentPane().add(button1);
			dialog.getContentPane().add(button2);
			
			button1.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					if(text1.getText().length()==0||text2.getText().length()==0)
					{
						return ;
					}
					server = text1.getText();
					timeout = text2.getText();
					writeSetting();
					dialog.dispose();
					
				}
				
			});
			
			button2.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					
					dialog.dispose();
				}
				
			});
			
			
			dialog.setVisible(true);
		}
	}
	class Run
	{
		private int width;
		private int height;
		private JDialog frame;
		private JButton button;
		Run(int w,int h)
		{
			width = w;
			height = h;
		}
		public void init()
		{
			frame = new JDialog();
			frame.setSize(100,100);
			frame.setLocation(width, height);
			button = new JButton("stop");
			frame.getContentPane().add(button);
			button.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					stop = true;
					frame.dispose();
					
				}
				
			});
			frame.addWindowListener(new WindowListener(){

				@Override
				public void windowActivated(WindowEvent e) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void windowClosed(WindowEvent e) {
					// TODO Auto-generated method stub
					
				}

				@Override
				public void windowClosing(WindowEvent e) {
					// TODO Auto-generated method stub
					stop = true;
					frame.dispose();
				}

				@Override
				public void windowDeactivated(WindowEvent e) {
					
				}

				@Override
				public void windowDeiconified(WindowEvent e) {
					
				}

				@Override
				public void windowIconified(WindowEvent e) {
					
				}

				@Override
				public void windowOpened(WindowEvent e) {
					
					
				}
				
			});
			frame.setVisible(true);
		}
		
	}
}
